package com.cn.lyl.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

public class Upload {
        public static void  file(HttpServletRequest req){

            DiskFileItemFactory factory = new DiskFileItemFactory();

            // 设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
            factory.setSizeThreshold(1024 * 1024);
            // 高水平的API文件上传处理,解析文件
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> list = null;
            try {
                list = upload.parseRequest(req);
            } catch (FileUploadException ex) {
                ex.printStackTrace();
            }

            // 获取上传的文件
            for (FileItem file : list) {
                FileItem item = file;
                System.out.println(item.getFieldName());
                System.out.println(item.getName());
                String name = item.getName();
               //添加时间戳防止重复
                String fileName = System.currentTimeMillis() + "---" + name;
                String temp = req.getServletContext().getRealPath("/");//服务器路径
                System.out.println(temp);
                String path = temp.split("out")[0] + "/web/";//真实路径
                String directory = "/img/";

//            文件夹不存在则创建文件夹
                File aa = IO.createDirectory(path + directory);
                try {
                    File tempFile = new File(aa, fileName);
                    item.write(tempFile);
                    File newFile = IO.createDirectory(temp + directory);
                    copy(tempFile, new File(newFile, fileName));
                    copy(tempFile,new File("D:/新建文件夹/folder/jsp/02/web/img/",fileName));
                    copy(tempFile,new File("D:/新建文件夹/folder/jsp/02/out/artifacts/02_war_exploded/img",fileName));
                    req.setAttribute("imgHref", directory + fileName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    private static void copy(File file, File newFile) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            OutputStream outputStream = new FileOutputStream(newFile);
            int lon = 0;
            while ((lon = inputStream.read()) != -1) {
                outputStream.write(lon);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
